#include <stdio.h>

//struct student
//{  
//	char num[9], name[20],   sex; 
//	int age,score[3],sum;  
//	float av;
//}st[3]={
//	{"06040106","Li Ping",   'M',    18,  87,89,91},
// 	{"06040125","Chen Fen",  'F',    19,  78,75,81},
// 	{"06040132","Wang Yifei",'M',    19,  65,67,69}};
//void count(struct student *p)
//{  
//	int i,j;
//	for(i=0;i<3;i++)
// 	{  
//	 	p[i].sum=0;
//		for(j=0;j<3;j++) p[i].sum+=p[i].score[j];
//		p[i].av=p[i].sum/3.0;
// 	}
//}
//int main()
//{  
//	int i,j;
// 	count(st);
// 	printf("The student's information:\n");
// 	printf("Num       Name        Sex  Age     Score    Sum  Average\n");
// 	for(i=0;i<3;i++)
// 	{  
//	 	printf("%-10s%-12s%-3c%5d  ",st[i].num,st[i].name,st[i].sex,st[i].age);
//		for(j=0;j<3;j++) printf("%3d",st[i].score[j]);
//		printf("%6d%9.1f\n",st[i].sum,st[i].av);
// 	}
// 	return 0;
//}
#define    N    5
typedef struct student {
  	long  sno;
  	char  name[10];
  	float  score[3];
} STU;
void fun(char  *filename)
{ 
	FILE  *fp;      int  i, j;
  	STU  s[N], t;
/**********found**********/
 	fp = fopen(filename, "r");
 	while(!feof(fp))
 	for(i=0;i<N;i++)
 	{
 		fscanf(fp,"%ld%-8s",&s[i].sno,s[i].name);
 		for(j=0;j<3;j++)
 			fscanf(fp,"%6.2f",&s[i].score[j]);
	}
  	fclose(fp);
  	for (i=0; i<N-1; i++)
    	for (j=i+1; j<N; j++)
/**********found**********/
      		if (s[i].sno > s[j].sno)
      		{  
			  	t = s[i];  
				s[i] = s[j];  
				s[j] = t;  
			}
  	fp = fopen(filename, "w");
/**********found**********/
 	for(i=0;i<N;i++)
 	{
 		fprintf(fp,"%ld %-8s",s[i].sno,s[i].name);
 		for(j=0;j<3;j++)
 			fprintf(fp,"%6.2f",s[i].score);
	}  
  	fclose(fp);
}
int main()
{ 
	STU  t[N]={ {10005,"ZhangSan", 95, 80, 88}, {10003,"LiSi", 85, 70, 78},
             {10002,"CaoKai", 75, 60, 88}, {10004,"FangFang", 90, 82, 87},
             {10001,"MaChao", 91, 92, 77}}, ss[N];
  	int  i,j;      
	FILE  *fp;
  	fp = fopen("student.dat", "w");
  	//fwrite(t, sizeof(STU), 5, fp);
  	for(i=0;i<N;i++)
 	{
 		fprintf(fp,"%ld%-8s",t[i].sno,t[i].name);
 		for(j=0;j<3;j++)
 			fprintf(fp,"%6.2f",t[i].score[j]);
	}  
  	fclose(fp);
  	printf("\n\nThe original data :\n\n");
  	for (j=0; j<N; j++)
  	{  
	  	printf("\nNo: %ld  Name: %-8s      Scores:  ",t[j].sno, t[j].name);
     	for (i=0; i<3; i++)  printf("%6.2f ", t[j].score[i]);
     	printf("\n");
  	}
  	fun("student.dat");
  	printf("\n\nThe data after sorting :\n\n");
  	fp = fopen("student.dat", "r");
  	//fread(ss, sizeof(STU), 5, fp);
  	for(i=0;i<N;i++)
 	{
 		fscanf(fp,"%ld %-8s",&ss[i].sno,ss[i].name);
 		for(j=0;j<3;j++)
 			fscanf(fp,"%6.2f",&ss[i].score[j]);
	}
  	fclose(fp);
  	for (j=0; j<N; j++)
  	{  
	  	printf("\nNo: %ld  Name: %-8s      Scores:  ",ss[j].sno, ss[j].name);
    	for (i=0; i<3; i++)  printf("%6.2f ", ss[j].score[i]);
    	printf("\n");
 	}
  return 0;
}
